<?php


namespace App\Http\Business;

use App\Models\Admin\AdminPower;
use Illuminate\Support\Facades\Auth;

class PowerBusiness extends BaseBusiness
{
    const POWER_CHECK_RESULT_TIME = 86400;       // 权限检测结果缓存时间 86400S = 24H
    const POWER_CHECK_RESULT_KEY = 'POWER_CHECK_RESULT_KEY_';
    const POWER_CHECK_VALUE_YES = 'yes';        //通过结果
    const POWER_CHECK_VALUE_NO = 'no';        //未通过结果

    public static function isSuperAdmin($phone)
    {
        $phones = config('permission.superAdmin');
        if(!empty($phones)){
            $phones = explode(',', $phones);
        }else{
            $phones = [];
        }

        return in_array($phone, $phones);
    }

    public function addNotAddPower()
    {
        $routes = app()->routes->getRoutes();
        foreach ($routes as $route){
            $ownMiddleware = $route->action['middleware'];
            // 只要需要权限验证路由才设置了权限验证中间件（admin.power）
            if (in_array('admin.power', $ownMiddleware)){
                $powerInfo = $this->_getPowerInfo($route->uri);
                AdminPower::firstOrCreate($powerInfo);
            }
        }
        return true;
    }

    public function checkPower($uri)
    {
        $cacheKeyFirst = self::POWER_CHECK_RESULT_KEY . $uri;
        $cacheValue = \Cache::get($cacheKeyFirst);
        if ($cacheValue == self::POWER_CHECK_VALUE_YES){
            return true;
        }
        $search = $this->_getPowerInfo($uri);
        $power = AdminPower::firstOrCreate($search);
        if ($power->is_check > 0){
            $user = Auth::guard('admin')->user();
            if ($user){
                //超级管理员具有所有权限
                if (self::isSuperAdmin($user->phone)){
                    return true;
                }
                $roles = [];
                $userRoles = $user->roles;
                foreach ($userRoles as $role){
                    $roles[] = $role->role_id;
                }
                sort($roles);
                $cacheKey = self::POWER_CHECK_RESULT_KEY . $uri . '_' . implode('_', $roles);
                $cacheValue = \Cache::get($cacheKey);
                if ($cacheValue == self::POWER_CHECK_VALUE_YES){
                    return true;
                }
                if ($cacheValue == self::POWER_CHECK_VALUE_NO){
                    return false;
                }
                $res = false;
                $roles2 = [];
                $powerRoles = $power->roles;
                foreach ($powerRoles as $powerRole){
                    $roles2[] = $powerRole->role_id;
                }
                if (!empty(array_intersect($roles, $roles2))){
                    $res = true;
                }

                $cacheValue = $res ? self::POWER_CHECK_VALUE_YES : self::POWER_CHECK_VALUE_NO;
                \Cache::put($cacheKey, $cacheValue, self::POWER_CHECK_RESULT_TIME);
                return $res;
            }else{
                return false;
            }
        }else{
            \Cache::put($cacheKeyFirst, self::POWER_CHECK_VALUE_YES, self::POWER_CHECK_RESULT_TIME);
            return true;
        }
    }


    protected function _getPowerInfo($uri)
    {
        $powerInfo = ['power' => $uri];
        $pathList = array_reverse(explode('/', $uri));
        $powerInfo['action'] = $pathList[0];
        unset($pathList[0]);
        $powerInfo['controller'] = ucfirst($pathList[1]);
        unset($pathList[1]);
        $powerInfo['module'] = implode('/', array_reverse($pathList));

        return $powerInfo;
    }

}
